﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace dis.sys.hw1.Model
{
    [DataContract]
    public class HotelRoom
    {
        [DataMember]
        public int RoomNumber { get; set; }

        [DataMember]
        public double Price { get; set; }

        [DataMember]
        public IDictionary<int,Tuple<DateTime,DateTime>> ReservedDates { get; set; }

        public HotelRoom(int roomNumber, double price)
        {
            RoomNumber = roomNumber;
            Price = price;
            ReservedDates = new ConcurrentDictionary<int, Tuple<DateTime, DateTime>>();
        }

        public bool IsAvailable(DateTime fromDate, DateTime toDate)
        {
            return
                !ReservedDates.Values.Any(
                    d => (d.Item1 >= fromDate && d.Item1 <= toDate) || (d.Item1 < fromDate && d.Item2 >= fromDate));
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public int Book(DateTime fromDate, DateTime toDate, int bookingId)
        {
            if (IsAvailable(fromDate, toDate))
            {
                ReservedDates[bookingId] = new Tuple<DateTime, DateTime>(fromDate, toDate);
                return bookingId;
            }
            throw new FaultException("Failed, the room " + RoomNumber + " is not available between " + fromDate.ToShortDateString() + " and " + toDate.ToShortDateString());
        }

        [MethodImpl(MethodImplOptions.Synchronized)]
        public void Unbook(int bookingId)
        {
            if (ReservedDates.ContainsKey(bookingId))
            {
                ReservedDates.Remove(bookingId);
            }
            else
            {
                throw new FaultException(bookingId + " is an invalid booking id");
            }
        }
    }
}
